In the browser
Now we can make a request to this PHP script from our JavaScript code:
$(document).ready(function() {
var $autocomplete = $('<ul class="autocomplete"></ul>')
.hide()
.insertAfter('#search-text');
$('#search-text').keyup(function() {
$.ajax({
'url': '../search/autocomplete.php',
'data': {'search-text': $('#search-text').val()},
'dataType': 'json',
'type': 'GET',
'success': function(data) {
if (data.length) {
$autocomplete.empty();
$.each(data, function(index, term) {
$('<li></li>').text(term).appendTo($autocomplete);
});
$autocomplete.show();
}
}
});
});
});
We need to use keyup, not keydown or keypress,
as the event that triggers the AJAX request. The latter two events
occur during the process of the key press, before the character has
actually been entered in the field. If we attempt to act on these
events and issue the request, the suggestion list will lag behind the
search text. When the third character is entered, for example, the AJAX
request will be made using just the first two characters. By acting on keyup, we avoid this problem.
In our stylesheet, we
position this list of suggestions absolutely, so that it overlaps the
text underneath. Now when we type in the search field, we see our
possible terms presented to us:
To properly display our list
of suggestions, we have to take into account the built-in
auto-completion mechanism of some web browsers. Browsers will often
remember what users have typed in a form field, and suggest these
entries the next time the form is used. This can look confusing when in
conjunction with our custom auto-complete suggestions:
Fortunately, this can be disabled in the browsers that perform autocompletion by setting the autocomplete attribute of the form field to off.
We could do this right in the HTML, but this would not be in keeping
with the principle of progressive enhancement because we would be
disabling the browser's autocompletion function without offering our
own. Instead, we can add this attribute from our script:
$('#search-text').attr('autocomplete', 'off')